package com.appbee.core.client.modular.impl;

import javax.inject.Inject;

import com.appbee.core.client.nav.SimpleNav;
import com.appbee.core.client.nav.SimpleNavRegistry;
import com.appbee.core.client.place.HasPlace;
import com.appbee.core.client.place.INamePlace;
import com.google.gwt.activity.shared.Activity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class ActivityProxy implements Activity
{

	private INamePlace namePlace;
	private final SimpleNavRegistry navRegistry;
	private Activity realActivity;
	private boolean canceled = false;

	@Inject
	public ActivityProxy(SimpleNavRegistry navRegistry)
	{
		this.navRegistry = navRegistry;
	}

	@Override
	public void start(final AcceptsOneWidget panel, final EventBus eventBus)
	{
		SimpleNav nav = navRegistry.getByPlace(namePlace);
		nav.getModul().setCurrentNavItem(nav);
		nav.getModul().getActivity(namePlace, new AsyncCallback<Activity>()
		{

			@Override
			public void onSuccess(Activity activity)
			{
				if (!canceled)
				{
					realActivity = activity;
					if (realActivity instanceof HasPlace)
					{
						((HasPlace) realActivity).setPlace((Place) namePlace);
					}
					realActivity.start(panel, eventBus);
				}
			}

			@Override
			public void onFailure(Throwable caught)
			{
			}
		});
	}

	@Override
	public String mayStop()
	{
		if (realActivity != null)
			return realActivity.mayStop();
		return null;
	}

	@Override
	public void onCancel()
	{
		if (realActivity != null)
		{
			realActivity.onCancel();
		}
		else
			canceled = true;
	}

	@Override
	public void onStop()
	{
		if (realActivity != null)
		{
			realActivity.onStop();
		}
		else
			canceled = true;
	}

	public void setPlace(INamePlace namePlace)
	{
		this.namePlace = namePlace;
	}
	
}
